package com.red.wine.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.ItemizedOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.OverlayItem;
import com.baidu.mapapi.map.PopupOverlay;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.model.Headers;
import com.red.wine.model.NodReqData;
import com.red.wine.model.NodeData;
import com.red.wine.model.NodeDataList;
import com.red.wine.model.NodeReq;
import com.red.wine.model.NodeReturn;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;
/**
 * 此demo用来展示如何结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置
 * 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 *
 */
public class PurchActivity extends Activity {
	
	// 定位相关
	LocationClient mLocClient;
	LocationData locData = null;
	public MyLocationListenner myListener = new MyLocationListenner();
	private ImageView city;
	private ImageView back;
	//定位图层
	locationOverlay myLocationOverlay = null;
	// 弹出泡泡图层
	private PopupOverlay pop = null;// 弹出泡泡图层，浏览节点时使用
	private TextView popupText = null;// 泡泡view
	private View viewCache = null;

	//地图相关，使用继承MapView的MyLocationMapView目的是重写touch事件实现泡泡处理
	//如果不处理touch事件，则无需继承，直接使用MapView即可
	MapView mMapView = null;	// 地图View
	private MapController mMapController = null;

	//UI相关
	OnCheckedChangeListener radioButtonListener = null;
	boolean isRequest = false;//是否手动触发请求定位
	boolean isFirstLoc = true;//是否首次定位
	boolean isLocationClientStop = false;
	private Context context;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_layout);
        context = this;
        city = (ImageView) findViewById(R.id.loaction_point_btn);
        back = (ImageView) findViewById(R.id.pay_back_btn_2);
		//地图初始化
        mMapView = (MapView)findViewById(R.id.bmapView);
        mMapController = mMapView.getController();
        mMapView.getController().setZoom(14);
        mMapView.getController().enableClick(true);
        mMapView.setBuiltInZoomControls(true);
      //创建 弹出泡泡图层
        
        //定位初始化
        mLocClient = new LocationClient( this );
        locData = new LocationData();
        mLocClient.registerLocationListener( myListener );
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);//打开gps
        option.setCoorType("bd09ll");     //设置坐标类型
        option.setScanSpan(5000);
        mLocClient.setLocOption(option);
        mLocClient.start();
       
        //定位图层初始化
		myLocationOverlay = new locationOverlay(mMapView);
		//设置定位数据
	    myLocationOverlay.setData(locData);
	    //添加定位图层
		mMapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		//修改定位数据后刷新图层生效
		mMapView.refresh();
		
		requestLocClick();
		
		city.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				PrefsUtils.setFrom("1");
				IntentUtil.redirectToNext(context, CityActivity.class);
				finish();
			}
		});
		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				IntentUtil.redirectToNext(context, MainActivity.class);
				finish();
			}
		});
		Log.e("TAG", "=========" + locData.latitude + " , " + locData.longitude);
    }
    /**
     * 手动触发一次定位请求
     */
    public void requestLocClick(){
    	isRequest = true;
        mLocClient.requestLocation();
        Toast.makeText(PurchActivity.this, "正在定位…", Toast.LENGTH_SHORT).show();
    }
    /**
     * 修改位置图标
     * @param marker
     */
    public void modifyLocationOverlayIcon(Drawable marker){
    	//当传入marker为null时，使用默认图标绘制
    	myLocationOverlay.setMarker(marker);
    	//修改图层，需要刷新MapView生效
    	mMapView.refresh();
    }
     
	/**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {
    	
    
        public void onReceiveLocation(BDLocation location) {
            if (location == null || isLocationClientStop)
                return ;
            locData.latitude = location.getLatitude();
            locData.longitude = location.getLongitude();
            //如果不显示定位精度圈，将accuracy赋值为0即可
            locData.accuracy = location.getRadius();
            locData.direction = location.getDerect();
            //更新定位数据
            myLocationOverlay.setData(locData);
            //更新图层数据执行刷新后生效
            mMapView.refresh();
            //是手动触发请求或首次定位时，移动到定位点
            if (isRequest || isFirstLoc){
            	//移动地图到定位点
                mMapController.animateTo(new GeoPoint((int)(locData.latitude* 1e6), (int)(locData.longitude *  1e6)));
                isRequest = false;
            }
            //首次定位完成
            isFirstLoc = false;
        }
        
        public void onReceivePoi(BDLocation poiLocation) {
            if (poiLocation == null){
                return ;
            }
        }
    }
    
    //继承MyLocationOverlay重写dispatchTap实现点击处理
  	public class locationOverlay extends MyLocationOverlay{

  		public locationOverlay(MapView mapView) {
  			super(mapView);
  			// TODO Auto-generated constructor stub
  		}
  		@Override
  		protected boolean dispatchTap() {
  			// TODO Auto-generated method stub
  			//处理点击事件,弹出泡泡
//  			popupText.setBackgroundResource(R.drawable.popup);
//			popupText.setText("我的位置");
//			pop.showPopup(BMapUtil.getBitmapFromView(popupText),
//					new GeoPoint((int)(locData.latitude*1e6), (int)(locData.longitude*1e6)),
//					8);
  			return true;
  		}
  		
  	}

    @Override
    protected void onPause() {
    	isLocationClientStop = true;
        mMapView.onPause();
        super.onPause();
    }
    
    private String key = "";
    NodeDataList datalist = null;
    private boolean isChoice = false;
    @Override
    protected void onResume() {
    	isLocationClientStop = false;
        mMapView.onResume();
        if(!StringUtil.isEmptyOrNull(PrefsUtils.getFrom())){
			if(PrefsUtils.getFrom().equals("1")){
				PrefsUtils.setFrom(null);
				isChoice = true;
			}
		}
        
        getData();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
    	//退出时销毁定位
        if (mLocClient != null)
            mLocClient.stop();
        isLocationClientStop = true;
        mMapView.destroy();
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	private void getData() {

		new ServiceAsynTask<NodeReturn>() {

			@Override
			protected NodeReturn callService() throws IOException,
					JsonParseException, AssertionError {
				NodeReq taste = new NodeReq();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				NodReqData data = new NodReqData();
				data.setLat(String.valueOf(locData.latitude));
				data.setLon(String.valueOf(locData.longitude));
				if(!StringUtil.isEmptyOrNull(PrefsUtils.getCityName())){
		        	isChoice = true;
		        	String[] strs = PrefsUtils.getCityName().split(":");
		        	if(strs != null && !StringUtil.isEmptyOrNull(strs[1])){
		        		key = strs[1];
		        	}
//		        	if(datasource != null && datasource.size() >0){
//		        		for(int i=0; i<datasource.size(); i++){
//		        			if(datasource.get(i).getCityname().equals(key)){
//		        				datalist = datasource.get(i);
//		        				choicedatasource.add(datalist);
//		        			}
//		        		}
//		        	}
		        } 
				data.setCityid(key);
				/*data.setNum("");
				data.setSince_id("");*/
				taste.cmd = "node_lists";
				taste.headers = header;
				taste.data = data;
				taste.sid = "7b8bb3e0152c9ed086f287ac37b927aa9085f2";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();
				PrefsUtils.setCityName(null);
				return ServiceHelper.getInstance().postData(urlstr, send,
						NodeReturn.class);
			}

			@Override
			protected void runWithResult(NodeReturn result) throws Exception {
				if (result != null) {
					bindData(result);
					Log.e("TAG", "isnotnull");
				} else {
					Toast.makeText(context, "获取酒庄列表失败", Toast.LENGTH_SHORT).show();
				}
				dialog.cancel();
			}

			@Override
			protected void runWithError(NodeReturn result, int iErrorCode)
					throws Exception {
			}
		}.execute();
	}

	private Dialog dialog;
	private NodeData nodedata = null;
	private List<NodeDataList> datasource = null;
	private List<NodeDataList> choicedatasource = null;
	private void bindData(NodeReturn result) {
		if (result.getRsp().equals("1")) {
			nodedata = result.getData();
			if(nodedata != null){
				datasource = nodedata.getItems();
			}
			if(datasource != null && datasource.size() > 0){
				Message msg = new Message();
				msg.what = 0x001;
				handler.sendMessage(msg);
			}
		} else {
			Toast.makeText(context, "获取酒庄列表失败", Toast.LENGTH_SHORT).show();
		}
//		dialog.cancel();
	}
	
	private MyOverlay mOverlay = null;
	private OverlayItem mCurItem = null;
	private View popView = null;
	private ArrayList<OverlayItem> mItems = null;
//	private Map<Integer, String> telmap = new HashMap<Integer, String>();
	private MapView.LayoutParams layoutParam = null;
	public class MyOverlay extends ItemizedOverlay {

		public MyOverlay(Drawable defaultMarker, MapView mapView) {
			super(defaultMarker, mapView);
		}

		@Override
		public boolean onTap(int index) {
			OverlayItem item = getItem(index);
			mCurItem = item;
			TextView name = (TextView) popView.findViewById(R.id.popu_pur_name);
			TextView address = (TextView) popView
					.findViewById(R.id.popu_pur_add);
			ImageView phone = (ImageView) popView
					.findViewById(R.id.pur_phone_img_btn);

			final NodeDataList info = datasource.get(index);
			name.setText(info.getTitle());
			address.setText(info.getAddress());
//			if (telmap.containsKey(phone.getId())) {
//				telmap.remove(index);
//			}
//			telmap.put(index, info.getTel());
			GeoPoint pt = item.getPoint();
			// 创建布局参数
			layoutParam = new MapView.LayoutParams(
			// 控件宽,继承自ViewGroup.LayoutParams
					MapView.LayoutParams.WRAP_CONTENT,
					// 控件高,继承自ViewGroup.LayoutParams
					MapView.LayoutParams.WRAP_CONTENT,
					// 使控件固定在某个地理位置
					pt, 0, -32,
					// 控件对齐方式
					MapView.LayoutParams.BOTTOM_CENTER);
			// 添加View到MapView中
			mMapView.addView(popView, layoutParam);
			phone.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					//传入服务， parse（）解析号码
	                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + info.getTel()));
	                //通知activtity处理传入的call服务
	                startActivity(intent);
				}
			});
			return true;
		}

		@Override
		public boolean onTap(GeoPoint pt, MapView mMapView) {
			mMapView.removeView(popView);
			return false;
		}
	}
	/** 覆盖物初始化 */
	public void initOverlay() {
		// 创建自定义overlay
		mOverlay = new MyOverlay(getResources().getDrawable(
				R.drawable.btn_earth_press), mMapView);
		if(isChoice){
			if (choicedatasource != null && choicedatasource.size() > 0) {
				for (int i = 0; i < choicedatasource.size(); i++) {
					double lat = Double.parseDouble(choicedatasource.get(i).getLat());
					double lon = Double.parseDouble(choicedatasource.get(i).getLon());
					GeoPoint point = new GeoPoint((int) (lat * 1E6),
							(int) (lon * 1E6));
					OverlayItem item = new OverlayItem(point, "覆盖物1", "");
					// 设置overlay图标，如不设置，则使用创建ItemizedOverlay时的默认图标.
					item.setMarker(getResources().getDrawable(
							R.drawable.btn_earth_press));
					mOverlay.addItem(item);
				}
			}
		}else{
		// 准备overlay 数据
			if (datasource != null && datasource.size() > 0) {
				for (int i = 0; i < datasource.size(); i++) {
					double lat = Double.parseDouble(datasource.get(i).getLat());
					double lon = Double.parseDouble(datasource.get(i).getLon());
					GeoPoint point = new GeoPoint((int) (lat * 1E6),
							(int) (lon * 1E6));
					OverlayItem item = new OverlayItem(point, "覆盖物1", "");
					// 设置overlay图标，如不设置，则使用创建ItemizedOverlay时的默认图标.
					item.setMarker(getResources().getDrawable(
							R.drawable.btn_earth_press));
					mOverlay.addItem(item);
				}
			}
		}

		// 保存所有item，以便overlay在reset后重新添加
		mItems = new ArrayList<OverlayItem>();
		mItems.addAll(mOverlay.getAllItem());

		// 将overlay 添加至MapView中
		mMapView.getOverlays().add(mOverlay);

		popView = LayoutInflater.from(this).inflate(R.layout.popview, null);
		
	}
	
	private Handler handler = new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		super.handleMessage(msg);
    		if(msg.what == 0x001){
    			if(!isChoice){
    			  if(datasource != null){
    				  try{
//    		        	mMapView.getOverlays().clear();
    		        	initOverlay();
    		        	 
    				  }catch (Exception e) {
    					  e.printStackTrace();
    				  }
    		        } else{
    		        	Toast.makeText(context, "暂未查找到", Toast.LENGTH_SHORT).show();
    		        }
    			}else{
    				if(choicedatasource != null){
      				  try{
//      		        	mMapView.getOverlays().clear();
      		        	initOverlay();
      				  }catch (Exception e) {
      					  e.printStackTrace();
      				  }
      		        } else{
      		        	Toast.makeText(context, "暂未查找到", Toast.LENGTH_SHORT).show();
      		        }
    			}
    			  if(dialog != null){
    				  dialog.cancel();
    			  }
    		} 
    	};
    };
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			IntentUtil.redirectToNext(context, MainActivity.class);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
